<?php
/**
 * Created by PhpStorm.
 * User: zcq
 * Date: 2018/10/22
 * Time: 17:24
 */

namespace app\common;

use AipOcr;

class Baidu
{
    private static $instance;
    public $appId;
    public $appKey;
    public $secret;
    public $access_token;
    private function __construct()
    {
        $config = config('setting');
        $this->appId = $config['baidu_app_id'];
        $this->appKey = $config['baidu_api_key'];
        $this->secret = $config['baidu_secret_key'];
//        $this->access_token = $this->getAccessToken();
    }

    public static function getInstance()
    {
        if(!isset(self::$instance)){
            self::$instance = new static();
        }
        return self::$instance;
    }

    public function getAccessToken()
    {
        $access_token = \cache('baidu_access_token');
        if($access_token!=null){
            $this->access_token = $access_token;
            return $this;
        }

        $url = 'https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id='.$this->appKey.'&client_secret='.$this->secret.'&';
        $res = $this->creat_curl($url);
        $res = json_decode($res,1);

        if(isset($res["error"])){
            trace('baidu_access_token:'.json_encode($res),'error');
            return false;
        }else{
            $expires_in = $res['expires_in'];
            $access_token = $res["access_token"];
            \cache('baidu_access_token',$access_token,$expires_in-100);
            $this->access_token = $res["access_token"];
            return $this;
        }
    }

    /**
     * 内容审核
     */
    public function verifyText($content)
    {
        if($content ==='' && $content === null)
            return false;
        if(!$this->access_token)
            return false;
        $url = 'https://aip.baidubce.com/rest/2.0/antispam/v2/spam?access_token='.$this->access_token;
        $post['content'] = $content;
//        $header = ['Content-Type:application/x-www-form-urlencoded'];

        $res = $this->creat_curl($url,$post);

        $res = json_decode($res,1);

        return $res;
    }

    /**
     * @param $url
     * @param null $data
     * @return mixed
     * curl访问https地址
     */
    public function creat_curl($url,$data=null,$header=null)
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL,$url);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        //post传输
        if($data){
            curl_setopt($ch,CURLOPT_POST,1);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        }
        if($header){
            curl_setopt($ch,CURLOPT_HTTPHEADER,$header);
        }
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        $res = curl_exec($ch);
        $error = curl_errno($ch);
        curl_close($ch);
        return $res;
    }
}